<?php
/**
 *    邮局汇款
 *
 *    @author    Garbin
 *    @usage    none
 */
class WeixinPayment extends BasePayment {
	var $_code = 'weixin';
	var $_gateway = 'https://mapi.alipay.com/gateway.do';

	/**
	 *    获取支付表单
	 *
	 *    @author    Garbin
	 *    @param     array $order_info  待支付的订单信息，必须包含总费用及唯一外部交易号
	 *    @return    array
	 */
	function get_payform($order_info,$returnUrl = '') {
		import("WxPayPubHelper/WxPayPubHelper");
		//使用jsapi接口
		$jsApi = new JsApi_pub();
		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		if (!isset($_GET['code']))
		{
			//触发微信返回code码
			//$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
			$returnUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$url = $jsApi->createOauthUrlForCode($returnUrl);
			Header("Location: $url"); 
		}else
		{
			//获取code码，以获取openid
		    $code = $_GET['code'];
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenId();
			if($openid == ''){
				Header("Location: ".SITE_URL."/mobile/index.php?app=cashier&order_id=".$_GET['order_id']); 
			}
		}
		
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		
		$unifiedOrder = new UnifiedOrder_pub();
		$unifiedOrder->setParameter("openid","$openid");//商品描述
		$unifiedOrder->setParameter("body","自贸直购-订单-".$order_info['order_sn']);//商品描述
		//自定义订单号，此处仅作举例
		$out_trade_no = $order_info['order_sn']."-".time();//商城订单号
		$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
		$total_fee = floatval(floatval($order_info['order_amount']) * 100);
		$total_fee = 1;
		$unifiedOrder->setParameter("total_fee",$total_fee);//总金额
		$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址 
		$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
		$order_id = $order_info['order_id'];
		$unifiedOrder->setParameter("attach","$order_id");//附加数据 
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
	
		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);
	
		$jsApiParameters = $jsApi->getParameters();
		
		//return $jsApiParameters;
		return $this->_create_payform( '',$jsApiParameters);
	}

	/**
	 *    返回通知结果
	 *
	 *    @author    Garbin
	 *    @param     array $order_info
	 *    @param     bool  $strict
	 *    @return    array
	 */
	function verify_notify($order_info, $strict = false) {
		if (empty($order_info))
        {
            echo 'order_info_empty';
            return false;
        }

        /* 初始化所需数据 */
        $notify =   $this->_get_notify();
        var_dump($notify);
        if($notify['return_code'] !="SUCCESS"){
			echo 'pay fault1:'.$notify['return_code'].'\n';
            return false;
		}
        if($notify['result_code'] !="SUCCESS"){
			echo 'pay fault:'.$notify['result_code'].'\n';
            return false;
		}
		if($notify['result_code'] =="SUCCESS"){
			$order_status = ORDER_ACCEPTED;
		}

        return array(
            'target'    =>  $order_status,
        );
	}
    
    function query_notify($order_info, $strict = false) {
        if (empty($order_info))
        {
            echo 'order_info_empty';
            return false;
        }
        //var_dump($order_info);
        $out_trade_no = $order_info["out_trade_sn"];
        import("WxPayPubHelper/WxPayPubHelper");
        //使用订单查询接口
        $orderQuery = new OrderQuery_pub();
        
        $orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
        
        //获取订单查询结果
        $orderQueryResult = $orderQuery->getResult();
        
        //商户根据实际情况设置相应的处理流程,此处仅作举例
        if ($orderQueryResult["return_code"] == "FAIL") {
            echo "error：".$orderQueryResult['return_msg']."<br>";
        }
        if($orderQueryResult["result_code"] == "FAIL"){
            echo "error：".$orderQueryResult['err_code']."<br>";
            echo "error_desc：".$orderQueryResult['err_code_des']."<br>";
        }
        //else{
            // echo "交易状态：".$orderQueryResult['trade_state']."<br>";
            // echo "设备号：".$orderQueryResult['device_info']."<br>";
            // echo "用户标识：".$orderQueryResult['openid']."<br>";
            // echo "是否关注公众账号：".$orderQueryResult['is_subscribe']."<br>";
            // echo "交易类型：".$orderQueryResult['trade_type']."<br>";
            // echo "付款银行：".$orderQueryResult['bank_type']."<br>";
            // echo "总金额：".$orderQueryResult['total_fee']."<br>";
            // echo "现金券金额：".$orderQueryResult['coupon_fee']."<br>";
            // echo "货币种类：".$orderQueryResult['fee_type']."<br>";
            // echo "微信支付订单号：".$orderQueryResult['transaction_id']."<br>";
            // echo "商户订单号：".$orderQueryResult['out_trade_no']."<br>";
            // echo "商家数据包：".$orderQueryResult['attach']."<br>";  
            //echo "支付完成时间：".$orderQueryResult['time_end']."<br>";
       // }   
        
        
        
        /* 初始化所需数据 */
        //$notify =   $this->_get_notify();
        // var_dump($notify);
       
        if($orderQueryResult['trade_state'] !="SUCCESS"){
            echo 'pay fault:'.$notify['result_code'].'\n';
            return false;
        }
        if($notify['result_code'] =="SUCCESS"){
            $order_status = ORDER_ACCEPTED;
        }

        return array(
            'target'    =>  $order_status,
        );
    }
}
?>